import { useEffect, useRef, forwardRef, useImperativeHandle } from "react";
import * as echarts from "echarts";
import type { EChartsOption } from "echarts";

interface GeneralProps {
  height: number;
  width?: string;
  option: any;
  onChartInit?: (chart: echarts.ECharts) => void;
}

const General = forwardRef<any, GeneralProps>(({ height = 200, width="100%", option, onChartInit }, ref) => {
  const chartRef = useRef<HTMLDivElement>(null);
  const chartInstance = useRef<echarts.ECharts | null>(null);

  useEffect(() => {
    if (!chartRef.current) return;
    
    // 初始化图表
    const chart = echarts.init(chartRef.current);
    chartInstance.current = chart;
    
    // 调用初始化回调
    if (onChartInit) {
      onChartInit(chart);
    }

    // 渲染图表
    chart.setOption(option);

    // 响应式处理
    const handleResize = () => {
      chart.resize();
    };
    window.addEventListener("resize", handleResize);

    // 清理函数
    return () => {
      chart.dispose();
      chartInstance.current = null;
      window.removeEventListener("resize", handleResize);
    };
  }, [option, onChartInit]);

  return (
    <div
      ref={chartRef}
      style={{
        // backgroundColor:"red",
        width: width,
        height: height || "100%",
        paddingTop: 0,
      }}
    />
  );
});

export default General;
